using AutoMapper;
using Domain.Material_Management;
using Infratructure.Interface;
using MediatR;
using MES.Server.API.Application.Command.Material_Management;
using ReturnValue;

namespace MES.Server.API.Application.Handler.Material_Management
{
    public class UpdateBomHandler : IRequestHandler<UpdateBomCommand, ApiResult<int>>
    {
        private readonly IRepository<BomModel> bomRepo;
        private readonly IMapper mapper;

        public UpdateBomHandler(IRepository<BomModel> bomRepo, IMapper mapper)
        {
            this.bomRepo = bomRepo;
            this.mapper = mapper;
        }

        /// <summary>
        /// 更新BOM信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(UpdateBomCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();

            // 验证BOM是否存在
            var existingBom = bomRepo.GetAll().Where(a => a.Id == request.Id && !a.IsDel).FirstOrDefault();
            if (existingBom == null)
            {
                result.Code = StatusCode.Fail;
                result.Message = "BOM不存在！";
                return await Task.FromResult(result);
            }

            // 检查编码是否重复（排除自己）
            var codeExists = bomRepo.GetAll().Where(a => a.BomCode == request.BomCode && a.Id != request.Id && !a.IsDel).FirstOrDefault();
            if (codeExists != null)
            {
                result.Code = StatusCode.Fail;
                result.Message = "该BOM编码已存在，请重新输入！";
                return await Task.FromResult(result);
            }

            // 更新字段
            existingBom.BomCode = request.BomCode;
            existingBom.BomName = request.BomName;
            existingBom.MaterialGroupId = request.MaterialGroupId;
            existingBom.BomVersion = request.BomVersion;
            existingBom.ProcessManagementId = request.ProcessManagementId;
            existingBom.UseNum = request.UseNum;
            existingBom.BomDesc = request.BomDesc;
            existingBom.UpdateTime = DateTime.Now;

            await bomRepo.UpdateAsync(existingBom);
            result.Code = StatusCode.Success;
            result.Message = "更新成功！";
            result.Data = 1;
            return await Task.FromResult(result);
        }
    }
}
